﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Andwp.AudioPlayer;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            string errorMsg;
            var listDevice = Player.GetDevices(out errorMsg);
            if (listDevice.Count == 0 && !string.IsNullOrEmpty(errorMsg))
            {

                return;
            }
            Console.WriteLine("输入设备对应的ID选择设备：");
            uint selectedId = 0;
            if (listDevice.Count == 1)
            {
                selectedId = listDevice[0].DeviceID;
                Console.WriteLine("自动选中{0}.{1}", selectedId, listDevice[0].Name);
            }
            else
            {
                foreach (var item in listDevice)
                {
                    Console.WriteLine(item.DeviceID + "." + item.Name);
                }
                bool readId = false;
                while (!readId)
                {
                    var input = Console.ReadLine();
                    readId = uint.TryParse(input, out selectedId);
                    if (readId && listDevice.Count <= selectedId)
                    {
                        readId = false;
                        Console.WriteLine("请输入正确的设备ID！");
                    }
                }
            }

            Player player = new Player();
            const int maxAllowPacket = 1000;
            player.MaxAllowUnhandleData = maxAllowPacket;

            if (player.Init(1, 9600, 8, (int)selectedId))
            {
                // 播放数据。。
                GenVoice(80, maxAllowPacket * 100, s => player.Play(s, 0, s.Length));

                Console.WriteLine("播放完毕！");
            }
            else
            {
                Console.WriteLine("初始失败！");
            }
        }

        /// <summary>
        /// 生成正玄单音波数据。
        /// </summary>
        /// <param name="mgc">增益</param>
        /// <param name="size">数据数量</param>
        /// <param name="callback">播放调用（边生成边播放）</param>
        private static void GenVoice(byte mgc, int size, Func<byte[], bool> callback)
        {
            const int point = 512;
            var tmpData = new byte[point];
            for (int i = 0; i < size; i++)
            {
                for (int j = 0; j < point; j++)
                {
                    tmpData[j] = (byte)((mgc) * Math.Sin(2 * Math.PI * (i * point + j) / 3.0));
                }
                Thread.Sleep(1);
                if (callback(tmpData) == false)
                {
                    Thread.Sleep(20);
                    Console.WriteLine("Buffer was full!");
                }
            }
        }
    }
}
